import { ref, computed } from "vue";
import { http } from "../http";
import { Car } from "../interface/car.interface";

export function useCar() {
  const car = ref({} as Car);

  async function addCar(book: string, number: number, order: string) {
    car.value = await http.post("/cars", {
      book,
      number,
      order,
    });
  }
  async function updateCar(id: string, number: number) {
    try {
      await http.patch(`/cars/${id}`, { number });
    } catch (e) {
      return false;
    }
    return true;
  }

  async function deleteCar(id: string) {
    try {
      await http.delete(`/cars/${id}`);
    } catch (e) {
      return false;
    }
    return true;
  }

  return {
    car,
    addCar,
    updateCar,
    deleteCar,
  };
}

export function useCars() {
  const cars = ref([] as Car[]);

  async function getCars(orderId: string) {
    cars.value = (await http.get(`/cars/${orderId}`)).data;
  }

  const calcPrice = computed(() => {
    let price = 0;
    for (let i of cars.value) {
      price += i.number * i.book.price;
    }
    return price.toFixed(2);
  });

  return {
    cars,
    getCars,
    calcPrice,
  };
}
